import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebPage4 extends StatefulWidget {
  const WebPage4({super.key});

  @override
  State<WebPage4> createState() => _WebPage4State();
}

class _WebPage4State extends State<WebPage4> {
  final textController = TextEditingController();
  double itemHeight = 0;
  // 1
  WebViewController controller = WebViewController();

  @override
  void initState() {
    super.initState();
    _initWebView();
  }

  _initWebView() async {
    // 2
    controller.loadRequest(Uri.parse("https://flutter.cn"));
  }

  @override
  Widget build(BuildContext context) {
    return Flex(
      direction: Axis.vertical,
      children: [
        Padding(
          padding: const EdgeInsets.all(4),
          child: _buildInputWidget(),
        ),
        Expanded(
          flex: 1,
          child: WebViewWidget(controller: controller),
        ),
        Container(
          height: itemHeight,
          color: Colors.redAccent,
        ),
      ],
    );
  }

  Widget _buildInputWidget() {
    return Flex(
      direction: Axis.horizontal,
      children: [
        Expanded(
          flex: 1,
          child: TextField(
            decoration: const InputDecoration(
              border: OutlineInputBorder(),
              hintText: 'https://flutter.cn',
            ),
            controller: textController,
          ),
        ),
        const Padding(padding: EdgeInsets.all(4)),
        ElevatedButton(
          child: const Text("加载"),
          onPressed: () {
            debugPrint("Load url: ${textController.text}");
            try {
              controller.loadRequest(Uri.parse(textController.text));
            } catch (e) {
              debugPrint("Load url error: $e");
            }
            debugPrint("Load url2: ${textController.text}");
          },
        ),
        const Padding(padding: EdgeInsets.all(4)),
        ElevatedButton(
          child: const Text("调整高度"),
          onPressed: () {
            setState(() {
              itemHeight = itemHeight < 400 ? itemHeight + 20 : 0;
            });
          },
        ),
      ],
    );
  }
}
